﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Sale_Common;
using Sale_Model;
using Sale_Operation;
namespace SaleSystem.ComPage
{
    public partial class frm_PutInUploadList : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request["Id"] != null)
                {
                    Id = ValueHandler.GetIntNumberValue(Request["Id"]);
                }
                FormatGrid(gv_List);
            }
      //      this.gv_List.PageIndexChange += new EventHandler<ExtAspNet.GridPageEventArgs>(gv_List_PageIndexChange);
        }

        protected void gv_List_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            gv_List.PageIndex = e.NewPageIndex;
            SortPags sp = new SortPags(dtDetail);
            this.gv_List.DataSource = sp.GetCurrentPage(LinkService.PageSize, gv_List.PageIndex+1); 
            this.gv_List.DataBind();
            this.gv_List.RecordCount = dtDetail.Rows.Count;
            this.gv_List.Title = "进货单明细，共[" + dtDetail.Rows.Count.ToString() + "]条";
            DataView dv = new DataView(dtDetail);
            dv.RowFilter = "IsError=0";
            if (dv.Count > 0)
                this.gv_List.Title += "错误信息<font color='red'>[" + dv.Count + "]</font>条";
         
        }
        protected void bnInput_Click(object sender, EventArgs e)
        {
            SModel.BBill_Id = Id;
            DataTable dtSave= Manager.GetDetail(SModel);
            if (SModel.BBill_Input == 1)
            {
                ExtAspNet.Alert.Show("该进货单已经入库，不能导入！");
                return;
            }
            else
            {
                dtSave.Rows.Clear();
                dtSave.AcceptChanges();
                DataTable dtCurrent =dtDetail;
                for(int i = 0 ; i <dtCurrent.Rows.Count;i++)
                {
                    if (dtCurrent.Rows[i]["IsError"].ToString() == "0")//校验不通过的，则不能导入
                        continue;
                    DataRow dr = dtSave.NewRow();
                    dr["BBDeta_SBill_Id"]=SModel.BBill_Id;
                    dr["BBDeta_PInfo_Id"] = dtCurrent.Rows[i]["ProductInfo"];
                    dr["BBDeta_Count"] = ValueHandler.GetIntNumberValue( dtCurrent.Rows[i]["数量"]);
                    dr["BBDeta_CostPrice"] = ValueHandler.GetDecNumberValue( dtCurrent.Rows[i]["成本价"]);
                    dr["BBDeta_Price"] = ValueHandler.GetDecNumberValue( dtCurrent.Rows[i]["零售价"]);
                    dr["BBDeta_Money"] = ValueHandler.GetDecNumberValue(dtCurrent.Rows[i]["数量"]) * ValueHandler.GetDecNumberValue(dtCurrent.Rows[i]["成本价"]);
                    dr["BBDeta_Memo"] = "";
                    dtSave.Rows.Add(dr);
                }
                SModel.BBill_Count = ValueHandler.GetIntNumberValue(dtSave.Compute("sum(BBDeta_Count)", ""));
                SModel.BBill_Money = ValueHandler.GetDecNumberValue(dtSave.Compute("sum(BBDeta_Money)", ""));
                bool blRes = Manager.Save(SModel, dtSave);
                if (blRes)
                {
                    ExtAspNet.Alert.Show("导入完成！", "提示！", "" + ExtAspNet.ActiveWindow.GetHideRefreshReference());

                }
                else
                {
                    ExtAspNet.Alert.Show("导入失败！", "操作提示", ExtAspNet.MessageBoxIcon.Error);
                }
              
            }
            
        }
        protected void bnUpload_Click(object sender, EventArgs e)
        {
            if (bn_Excel.FileName.ToString() == "")
            {
                ExtAspNet.Alert.Show("请选择要导入的文件！");
                return;
            }
            string strName = System.DateTime.Now.ToString("yyyyMMddhhmmss")+".xls";
            string M_ApplicationPath = Request.ApplicationPath;
            if (M_ApplicationPath == "")
                M_ApplicationPath = "/";
            if (!M_ApplicationPath.EndsWith("/"))
                M_ApplicationPath += "/";
            bn_Excel.SaveAs(Server.MapPath( M_ApplicationPath )+ "/Upload/" + strName);
            DataTable dt = ExcelHandler.GetTableFrom(Server.MapPath(M_ApplicationPath) + "/Upload/" + strName, "入库单模版");
            dt.Columns.Add("ProductInfo");//导入的产品的ID
            dt.Columns.Add("IsError",typeof(System.Int16));//IsError 0:则该产品有问题，不能插入到进货单中, 1:则没有问题，可以插入
            dt.Columns.Add("ErrorMessage");//存储错误信息
            
            int iUserId= LinkService.GetCurrentUser().SUser_Id;
            #region 1）将每个产品插入数据库中，如果该产品在数据库中存在，则将该产品信息(ProductInfo)从数据库中取出，并放到内存中
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                try
                {
                    //插入该产品前，先校验该产品类别是否存在          
                    ProductSortOp SortOp = new ProductSortOp();
                    ProductSort SortSM = new ProductSort();
                    SortSM.PSort_Name = ValueHandler.GetStringValue(dr["产品类别"], ValueHandler.CharHandlerType.IsRepChar);
                    SortSM = SortOp.GetModel(SortSM);
                    dr["IsError"] = 0;
                    //大类不存在，则跳过
                    if (SortSM.PSort_ID == 0)
                    {                       
                        dr["ErrorMessage"] = "该产品大类不存在，请在数据库中添加后再做此操作！";
                        continue;
                    }
                    //校验产品编码是否重复
                    ProductInfoOp ProductOp = new ProductInfoOp();
                    ProductInfo ProductSM = new ProductInfo();
                    ProductSM.PInfo_Code = ValueHandler.GetStringValue(dr["产品编码"], ValueHandler.CharHandlerType.IsRepChar);
                    ProductSM.PInfo_Name = ValueHandler.GetStringValue(dr["产品名称"], ValueHandler.CharHandlerType.IsRepChar);
                    ProductSM.PInfo_Cost = ValueHandler.GetDecNumberValue(ProductSM.PInfo_Cost);
                    ProductSM.PInfo_Price = ValueHandler.GetDecNumberValue(ProductSM.PInfo_Price);
                    if (ProductSM.PInfo_Name.Trim() != "")
                    {
                        ProductSM = ProductOp.GetModelByName(ProductSM);
                    }
                    if (ProductSM.PInfo_Id != 0)
                    {
                        dr["ProductInfo"] = ProductSM.PInfo_Id;
                        dr["产品编码"] = ProductSM.PInfo_Code;

                        dr["IsError"] = 1;
                    }
                    else
                    {
                        //新增产品
                        ProductSM.PInfo_Code= Coder.CreateCoder(EMenuList.产品管理);
                        ProductSM.CreateMan = iUserId;
                        ProductSM.CreateTime = System.DateTime.Now;
                        ProductSM.PInfo_CH = ValueHandler.GetStringValue(dr["串号"], ValueHandler.CharHandlerType.IsRepChar);
                        ProductSM.PInfo_Cost = ValueHandler.GetDecNumberValue(dr["成本价"]);
                        ProductSM.PInfo_Number = ValueHandler.GetStringValue(dr["号码"], ValueHandler.CharHandlerType.IsRepChar);
                        ProductSM.PInfo_Price = ValueHandler.GetDecNumberValue(dr["零售价"]);
                        ProductSM.PInfo_PSort_ID = SortSM.PSort_ID;
                        ProductSM.PInfo_Pwd = ValueHandler.GetStringValue(dr["密码"], ValueHandler.CharHandlerType.IsRepChar);
                        ProductSM.State = 1;
                        ProductSM.PInfo_Memo = ValueHandler.GetStringValue( dr["备注"]);
                        bool blRes = ProductOp.Save(ProductSM);
                        if (blRes)
                        {
                            dr["ProductInfo"] = ProductSM.PInfo_Id;
                            dr["产品编码"] = ProductSM.PInfo_Code;
                            dr["IsError"] = 1;
                        }
                        else
                        {
                            dr["IsError"] = 0;
                            dr["ErrorMessage"] = "产品导入到数据库中失败,请查看操作日志！";
                        }
                    }
                }
                catch (Exception ex)
                {
                    dr["IsError"] = 0;
                    dr["ErrorMessage"] = ex.ToString();
                }
            }
            #endregion
            #region 将内存中标志为正确的数据，保存到该入库单中
            gv_List.PageSize = LinkService.PageSize;
            SortPags sp = new SortPags(dt);
            this.gv_List.DataSource = sp.GetCurrentPage(LinkService.PageSize, gv_List.PageIndex+1); 
            this.gv_List.DataBind();
            this.gv_List.RecordCount = dt.Rows.Count;
            this.gv_List.Title = "进货单明细，共["+dt.Rows.Count.ToString()+"]条";
            DataView dv = new DataView(dt);
            dv.RowFilter = "IsError=0";
            if (dv.Count > 0)
                this.gv_List.Title += "错误信息<font color='red'>["+dv.Count+"]</font>条";
            this.bnInput.Hidden = false ;
            dtDetail = dt;
            #endregion
        }
        #region
        public DataTable dtDetail
        {
            get
            {
                return ViewState["dtDetail"] as DataTable;
            }
            set
            {
                ViewState["dtDetail"] = value;
            }
        }
        BuyBillOp Manager = new BuyBillOp();
        new Sale_Model.BuyBill SModel = new Sale_Model.BuyBill();
        #endregion
    }
}
